Parsing and formatting currency
Now, we can move on to the
totals in the right-hand column. Each row's total cost should be
calculated by multiplying the quantity entered by the price of that
item. Since we're now performing multiple tasks for each row, we can
begin by refactoring the quantity calculations a bit to be row-based
rather than field-based:
$('#cart tbody tr').each(function() {
var quantity = parseInt($('td.quantity input', this).val());
totalQuantity += quantity;
});
This produces the same result as before, but we now have a convenient place to insert our total cost calculation for each row:
$('td.quantity input').change(function() {
var totalQuantity = 0;
$('#cart tbody tr').each(function() {
var price = parseFloat($('td.price', this).text()
.replace(/^[^\d.]*/, ''));
price = isNaN(price) ? 0 : price;
var quantity =
parseInt($('td.quantity input', this).val());
var cost = quantity * price;
$('td.cost', this).text('$' + cost);
totalQuantity += quantity;
});
$('tr.shipping td.quantity').text(String(totalQuantity));
});
We fetch the price of each item
out of the table using the same technique we needed when sorting tables
by price earlier. The regular expression first strips the currency
symbols off from the front of the value, and the resulting string is
then sent to parseFloat(), which
interprets the value as a floating-point number. Since we will be doing
calculations with the result, we need to check that a number was found,
and set the price to 0 if not. Finally, we multiply the cost by the quantity, and then place the result in the total column with a $ preceding it. We can now see our total calculations in action: